const {readFileSync, writeFileSync} = require("fs");

const reg = /\/\*\*\s((.|\s)*?)\s\*\//m
const importRB = /import\(('|"|`)\.\/.+?('|"|`)\)\./m
const importRF = /import\(('|"|`)\.\/.+?('|"|`)\)\.(\w+)/m

/**
 * 
 * @param {String} text 
 */
function buildJsDoc(text) {
    let newText = text
    let temp = text
    let match = reg.exec(temp)[0]
    while (match) {
        if (importRF.exec(match) && match.startsWith('/**') && match.endsWith('*/')) {
            let importTemp = match
            let importMatch = importRF.exec(importTemp)[0]
            let newMatch = match;
            while (importMatch) {
                if (importRB.exec(importTemp) !== null){
                    newIM = importMatch.replace(importRB.exec(importTemp)[0], '')
                    newMatch = newMatch.replace(importMatch, newIM)
                }
                importTemp = importTemp.replace(importMatch, '')
                if (importRF.exec(importTemp) !== null)
                    importMatch = importRF.exec(importTemp)[0]
                else 
                    importMatch = null
            }
            newText = newText.replace(match,newMatch)
        }
        temp = temp.replace(match, '')
        if (reg.exec(temp) !== null)
            match = reg.exec(temp)[0]
        else
            match = null
    }
    return newText
}

const timeold = new Date().getTime();
writeFileSync('./dist/mysql.cjs.js', buildJsDoc(readFileSync('./dist/mysql.cjs.js', 'utf-8').toString()));
writeFileSync('./dist/mysql.esm.js', buildJsDoc(readFileSync('./dist/mysql.esm.js', 'utf-8').toString()));
console.log(`Build time: ${new Date().getTime() - timeold}ms`)